const mongoose = require('mongoose')
const db = 'mongodb://localhost/smilevue'
const glob = require('glob')
const { resolve } = require('path')

exports.initSchemas = () => {
  glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}


exports.connect = () => {
  let maxConnectTimes = 0
  return new Promise((resolve, reject) => {
      // 连接数据库
      mongoose.set('useCreateIndex', true) //加上这个
      mongoose.connect(db, {
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      //增加数据库连接的事件监听
      mongoose.connection.on('disconnect', () => {
        console.log('***********数据库断开**********')
        if (maxConnectTimes < 3) {
          maxConnectTimes++
          mongoose.connect(db)
        } else {
          reject()
          throw new Error('数据库出现问题，程序无法运行')
        }
      })
      //数据库出现错误的时候
      mongoose.connection.on('error', () => {
        console.log('***********数据库错误**********')
        if (maxConnectTimes < 3) {
          maxConnectTimes++
          mongoose.connect(db)
        } else {
          reject()
          throw new Error('数据库出现问题，程序无法运行')
        }
      })
      // 链接打开的shihou
      mongoose.connection.once('open', () => {
        // mongoose.connect(db)
        console.log('mongoose connect successfully')
        resolve()
      })
  })
}